<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" plain @click="addroledialog">添加社区</el-button>
    </div>
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 150px;" class="filter-item" clearable placeholder="社区名称" v-model="listQuery.name">
      </el-input>
      <el-select clearable v-model="listQuery.provinceId" placeholder="请选择" @change="getcity">
        <el-option
          v-for="item in provinceLIst"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-select clearable v-model="listQuery.cityId" placeholder="请选择" @change="getdistrict">
        <el-option
          v-for="item in cityList"
          :key="item.code"
          :label="item.name"
          :value="item.code"
          change="getarea">
        </el-option>
      </el-select>
      <el-select clearable v-model="listQuery.districtId" placeholder="请选择" @change="getstreet">
        <el-option
          v-for="item in districtList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-select clearable v-model="listQuery.streetId" placeholder="请选择">
        <el-option
          v-for="item in streetList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='ID' width="160">
        <template slot-scope="scope">
          {{scope.row.code}}
        </template>
      </el-table-column>
      <el-table-column label="社区名称" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="省市区" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.provinceName}},{{scope.row.cityName}},{{scope.row.districtName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="街道" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.streetName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="bianji(scope.row,scope.$index)" plain>编辑</el-button>
          <el-button type="danger" size="mini" @click="shanchu(scope.row, scope.$index)" plain>删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--编辑表单弹窗-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="formsrules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 525px; margin-left:50px;'>
        <el-form-item label="社区名称：" prop="name">
          <el-input v-model="temp.name" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="社区编码：" prop="code">
          <el-input v-model="temp.code" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'" label="城市选择：" prop="provinceId">
          <el-select v-model="temp.provinceId" placeholder="请选择" @change="getcity">
            <el-option
              v-for="item in provinceLIst"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
          <el-select v-model="temp.cityId" placeholder="请选择" @change="getdistrict">
            <el-option
              v-for="item in cityList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              change="getarea">
            </el-option>
          </el-select>
          <el-select v-model="temp.districtId" placeholder="请选择" @change="getstreet">
            <el-option
              v-for="item in districtList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
          <el-select v-model="temp.streetId" placeholder="请选择">
            <el-option
              v-for="item in streetList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addrole">确 定</el-button>
        <el-button v-else type="primary" @click="sureEdit">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑表单弹窗END-->

    <!--分页-->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30,50]"
                     :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!--分页END-->
  </div>
</template>

<script>
  import { getList, addroles, sureEdit, shanchu } from '@/api/region/community'
  import { getareaList } from '@/api/public'

  export default {
    data() {
      var checkletter = (rules, value, callback) => {
        const letter = /^[A-Z]+$/
        if (!value) {
          return callback(new Error('请输入编码'))
        } else if (value.length !== 4) {
          return callback(new Error('请输入四位的编码'))
        } else if (!letter.test(value)) {
          return callback(new Error('请输入大写的编码'))
        } else {
          callback()
        }
      }
      return {
        list: null,
        listLoading: true,
        total: null,
        listQuery: {
          id: undefined,
          name: '',
          provinceId: '',
          cityId: '',
          districtId: '',
          streetId: ''
        },
        provinceLIst: [],
        cityList: [],
        districtList: [],
        streetList: [],
        temp: {
          id: undefined,
          name: '',
          code: '',
          provinceId: '',
          cityId: '',
          districtId: '',
          streetId: ''
        },
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogFormVisible: false,
        formsrules: {
          code: [{ required: true, trigger: 'blur', validator: checkletter }],
          name: [{ required: true, message: '请输入', trigger: 'blur' }],
          provinceId: [{ required: true, message: '请选择', trigger: 'change' }],
          cityId: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        selected: [],
        selected2: []
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          normal: '正常',
          disble: '停止'
        }
        return statusMap[status]
      }
    },
    created() {
      this.fetchData()
      this.getarea()
    },
    methods: {
      // 获取列表
      fetchData() {
        this.listLoading = true
        getList(this.listQuery).then(response => {
          this.list = response.data.content
          this.total = response.data.totalElements
          this.listQuery.size = response.data.size
          this.listLoading = false
        })
      },
      getarea() {
        getareaList(undefined).then(res => {
          this.provinceLIst = res.data
        })
      },
      getcity(value) {
        getareaList(value).then(res => {
          this.cityList = res.data
        })
      },
      getdistrict(value) {
        getareaList(value).then(res => {
          this.districtList = res.data
        })
      },
      getstreet(value) {
        getareaList(value).then(res => {
          this.streetList = res.data
        })
      },
      handleFilter() {
        this.fetchData()
      },
      addroledialog() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          code: '',
          provinceId: '',
          cityId: '',
          districtId: '',
          streetId: ''
        }
      },
      addrole() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addroles(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              location.reload()
            })
          }
        })
      },
      bianji(row) {
        this.temp = Object.assign({}, row)
        this.selected.push(row.provinceId)
        this.selected.push(row.cityId)
        this.selected.push(row.districtId)
        if (row.streetId === null) {
          console.log(0)
        } else {
          this.selected.push(row.streetId)
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      sureEdit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const temData = Object.assign({}, this.temp)
            this.temp.provinceId = this.selected[0]
            this.temp.cityId = this.selected[1]
            this.temp.districtId = this.selected[2]
            this.temp.streetId = this.selected[3]
            sureEdit(temData).then(response => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      shanchu(row) {
        this.$confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          shanchu(row.uuid).then(() => {
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.fetchData()
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .filter-container{
    padding-bottom: 10px;
  }
  .area-select .el-select{
    margin-left: 0;
  }
</style>
